package com.fzy.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    // 替换为你的实际信息
    private static final String VALID_USERNAME = "fanzhenyu"; // 姓名全拼
    private static final String VALID_PASSWORD = "2124";     // 学号后四位

    // 处理 GET 请求，可重定向到登录页面
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.sendRedirect("login.html");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("psw");
        try {
            // 加载MySQL JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = new LoginServlet().getConnection();
            Statement stmt =conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from user");
            while (rs.next()) {
                String name = rs.getString("username");
                String psw = rs.getString("psw");
                if (name.equals(username) && psw.equals(password)) {
                    request.getRequestDispatcher("success.html").forward(request, response);
                } else {
                    request.getRequestDispatcher("failure.html").forward(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    public static Connection getConnection() throws SQLException {
        // 数据库连接 URL
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
        // 数据库用户名
        String user = "root";
        // 数据库密码
        String password = "13100140892Fzy!";
        // 获取数据库连接
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }
}